package cn.gov.sdcj.accountancy.entity

import groovy.transform.AutoClone

/**
 * <p>Description: 会计凭证分录对象</p>
 *
 * <li>id 为 凭证分录号</li>
 * <li>exp 为 摘要</li>
 * <li>accountNum 为 科目编码（含全部级次）</li>
 * <li>accountName 为 科目名称（全称）</li>
 * <li>amount 为 金额</li>
 * <li>dc 为 借贷方向，0=贷，1=借</li>
 * <li>items 为 辅助核算</li>
 * <li>relations 为 与支付凭证的关联关系</li>
 * <p />
 *
 * Created by laijie on 2015/3/27.
 */
@AutoClone
class Entry {
    int voucherId;
    int id;
    String exp;
    String accountNum;
    String accountName;
    BigDecimal amount;
    int dc;
    List<Item> items = new ArrayList<Item>();
    List<Relation> relations = new ArrayList<Relation>();

    void setVoucherId(int id) {
        this.voucherId = id
        items.each {
            it.setVoucherId(id)
        }
        relations.each {
            it.setVoucherId(id)
        }
    }

    void setId(int id) {
        this.id = id
        items.each {
            it.setEntryId(id)
        }
        relations.each {
            it.setEntryId(id)
        }
    }

    def add(Item item) {
        items.add(item)
    }

    def add(Relation relation) {
        relations.add(relation)
    }

    def add(Map attributes) {
        attributes.each { it ->
            if (this.hasProperty("$it.key")) {
                // 属性已有则进行连接
                if (this.getProperty(it.key)) {
                    this["$it.key"] += it.value
                } else {
                    this["$it.key"] = it.value
                }
            }
        }
    }

    String toString() {
        String rst = "($id)${dc ? '借' : '贷'}: ${accountNum}[${accountName}]"
        items.each {
            rst += "|{$it}"
        }
        rst += "; (￥$amount); (摘要: $exp); "
        rst += " --> "
        relations.each {
            rst += "${it},"
        }
        return rst
    }

    boolean equals(Object obj) {
        return (obj in Entry
                && exp == obj.exp
                && accountNum == obj.accountNum
                && accountName == obj.accountName
                && dc == obj.dc
                && items.containsAll(obj.items)
                && obj.items.containsAll(items)
        )
    }

    Entry plus(Entry other) {
        Entry entry = this.clone();
        if (equals(other)) {
            entry.amount += other.amount
            entry.relations.addAll(other.relations);
        }
        return entry
    }
}
